import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/event.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/common/local_storage.dart';
import 'package:flutter_smart_heating/config/config.dart';
import 'package:flutter_smart_heating/pages/user/login/login.dart';
import 'package:get/get.dart';

class AuthService extends GetxService {
  late UserData user;

  /// 初始化
  Future<AuthService> init() async {
    await getUserInfo();
    return this;
  }

  /// 获取用户信息
  Future getUserInfo() async {
    var res = await Http.instance.post('/api/user/index');
    if (res.code == 1) {
      user = UserData.fromJson(res.data);
    } else {
      user = UserData();
    }
    return this;
  }

  refresh() async {
    await getUserInfo();
    update();
  }

  int get substationId => user.substationId ?? 0;

  /// 是否登录
  bool get isLogined => user.userId != null;

  /// 判断是否登录，未登录则打开登录页面
  Future<bool> isLoginOrToLogin({String? title}) async {
    if (!isLogined) {
      var result = await App.pushRoute(
        Get.context,
        const LoginPage(),
        fullscreenDialog: true,
      );
      await 0.4.delay();
      return result == true;
    }

    return true;
  }

  String sign() {
    var timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    int randomNum = Random().nextInt(10);
    var sign = App.md5(
        '$timestamp##${user.id}##$randomNum##${Config.appKey}##$timestamp');
    sign =
        '${sign.substring(0, 16)}.${user.id}.$randomNum.${sign.substring(16, 32)}';
    var token = App.md5('$timestamp##$sign##${Config.appKey}##$timestamp');
    return 'token=$token&sign=$sign&timestamp=$timestamp';
  }

  Future update({String action = 'all'}) async {
    await Get.forceAppUpdate();
    AppEvent.instance.eventBus.fire(UserChangeEvent(user, action));
    debugPrint('UserInfoUpdate');
  }

  /// 登录，通过token登录
  Future<bool> login(String token) async {
    LocalStorage.instance.setItem('user.token', token);
    await getUserInfo();
    await update();
    return isLogined;
  }

  /// 退出登录
  Future<bool> logout() async {
    await Http.instance.post('/plugin/j_push/api/unbindRegistrationId');
    Http.instance.post('/api/user/public/logout');
    LocalStorage.instance.removeItem('user.token');
    user = UserData();
    //Get.forceAppUpdate();
    //Get.reload(force: true);
    return true;
  }

  static AuthService get instance => Get.find<AuthService>();
}

class UserData {
  int? id;
  int? userId;
  String? avatar;
  String? mobile;
  String? userEmail;
  String? userNickname;
  String? userLogin;
  String? name;
  String? intro;
  bool? isAuthentication;
  bool? isSubstation;
  bool? isVip;
  int? substationId;
  String? substationName;
  int? remainingDays;

  UserData({
    this.id,
    this.userId,
    this.avatar,
    this.mobile,
    this.userEmail,
    this.userNickname,
    this.userLogin,
    this.name,
    this.intro,
    this.isAuthentication,
    this.isVip,
    this.isSubstation,
    this.substationId,
    this.substationName,
    this.remainingDays,
  });

  UserData.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    userId = json['user_id'];
    avatar = json['avatar'];
    mobile = json['mobile'];
    userEmail = json['user_email'];
    userNickname = json['user_nickname'];
    userLogin = json['user_login'];
    name = json['name'];
    intro = json['intro'];
    isAuthentication = json['is_authentication'];
    isVip = json['is_vip'];
    isSubstation = json['is_substation'];
    substationId = json['substation_id'];
    substationName = json['substation_name'];
    remainingDays = json['remaining_days'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};
    data['id'] = id;
    data['user_id'] = userId;
    data['avatar'] = avatar;
    data['mobile'] = mobile;
    data['user_email'] = userEmail;
    data['user_nickname'] = userNickname;
    data['user_login'] = userLogin;
    data['name'] = name;
    data['intro'] = intro;
    data['is_authentication'] = isAuthentication;
    data['is_vip'] = isVip;
    data['is_substation'] = isSubstation;
    data['substation_id'] = substationId;
    data['substation_name'] = substationName;
    data['remaining_days'] = remainingDays;
    return data;
  }
}
